package com.example.yc23.demo.util;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class UpLoadController {
    public static final String IMAGE_PATH="F://film_review/image/";
    public static final String VIDEO_PATH="F://film_review/video/";
   public String PATH=null;
    @PostMapping({"/upload/image","/upload/video"})//RequestPart用来在文件上传的请求中指定http请求参数名
    @ResponseBody
    public Map<String,Object> uploadImage(@RequestPart("file") MultipartFile file, HttpServletRequest request) throws IOException {

        if (request.getRequestURI().contains("/upload/image")){
            PATH=IMAGE_PATH;
        }
        if (request.getRequestURI().contains("/upload/video")){
            PATH=VIDEO_PATH;
        }
        //封装上传图片的逻辑
        Map result=new HashMap();
        if (!file.isEmpty()){//判断文件不为空时才保存图片
            if (!new File(PATH).exists()) {
                new File(PATH).mkdirs();
            }
            //获取上传图片的后缀
            String extension= StringUtils.getFilenameExtension(file.getOriginalFilename());
            //替换文件的-，拼接一个不会重复的文件名
            String filename= UUID.randomUUID().toString().replaceAll("-","")+"."+extension;
            //保存图片
            file.transferTo(new File(PATH+filename));
            result.put("isok",1);//上传成功
            result.put("filename",filename);//将文件名返回给客户端

        }else{
            result.put("isok",0);
            result.put("msg","文件不能为空");
        }
        return result;
    }

    @RequestMapping("/image/{filename}")
    @ResponseBody
    public void image(@PathVariable String filename, OutputStream outputStream) throws IOException {
        if(!new File(IMAGE_PATH+filename).exists()){
            filename="image_lose.jpg";
        }
        IOUtils.copy(new FileInputStream(IMAGE_PATH+filename),outputStream);
        // IOUtils.copy将一个流拷贝到另外一个流当中
    }
    @RequestMapping("/video/{filename}")
    @ResponseBody
    public void video(@PathVariable String filename, OutputStream outputStream) throws IOException {
        if(!new File(VIDEO_PATH+filename).exists()){
            filename="image_lose.jpg";
        }
        IOUtils.copy(new FileInputStream(VIDEO_PATH+filename),outputStream);
        // IOUtils.copy将一个流拷贝到另外一个流当中
    }

}
